package com.taptech.doufu.ui.adapter;

import android.util.SparseArray;

import com.taptech.doufu.ui.fragment.NovelChildFragments.SectionDetailsFragment;
import com.taptech.doufu.ui.fragment.NovelReadEndFragment;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

/**
 * 小说内容页面适配器
 */
public class NovelSectionDetailsAdapter extends FragmentPagerAdapter {
    private List<Fragment> fragments;

    public NovelSectionDetailsAdapter(FragmentManager fm, SparseArray<String> list, String novelId) {
        super(fm);
        if (list != null) {
            fragments = new ArrayList<>();
            for (int i = 0 ; i < list.size() ; i++){
                fragments.add(SectionDetailsFragment.newInstance(list.get(i), novelId,null, i+1, list.size()));
            }
            if(list.size() > 0){
                fragments.add(NovelReadEndFragment.Companion.newInstance(novelId));
            }
        }
    }

    public NovelSectionDetailsAdapter(FragmentManager fm, SparseArray<String> list,String topic, String novelId) {
        super(fm);
        if (list != null) {
            fragments = new ArrayList<>();
            try {
                for (int i = 0 ; i < list.size() ; i++){
                    fragments.add(SectionDetailsFragment.newInstance(list.get(i), novelId,topic, i+1, list.size()));
                }
            } catch (Exception e) {

            }

            if(list.size() > 0){
                fragments.add(NovelReadEndFragment.Companion.newInstance(novelId));
            }
        }
    }

    public void refush(SparseArray<String> list,org.json.JSONArray offlineArray,String offlineTopicData){
            for (int i = 0 ; i < list.size() ; i++){
                Fragment fragment = fragments.get(i);
                if (fragment instanceof SectionDetailsFragment) {
                    SectionDetailsFragment item = (SectionDetailsFragment) fragment;
                    if (item != null) {
                        try {
                            JSONObject offlineData = offlineArray.getJSONObject(i);
                            item.updateOffLine(offlineData.toString(),offlineTopicData);
                        } catch (Exception e) {
                            System.out.println("离线更新：error==>"+e.getMessage());
                        }
                    }
                }
            }

    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}
